import { Alert, Image, StyleSheet, Text, TextInput, View } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import ZhPage from "./ZhPage";
import UIConstants from '../constants/UIConstants';   //ES6的模块导入语法
let logo = require('../assets/img/logo.png')           //CommonJS模块导入语法
import AntDesign from '@expo/vector-icons/AntDesign';
import Ionicons from '@expo/vector-icons/Ionicons';
import ZhButton from '../components/ZhButton';
import userModel from '../viewmodels/UserModel';
import Toast from 'react-native-root-toast';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function ZhLogin() {
  let [phone, setPhone] = useState('')      //使用钩子函数创建 电话号码
  let [pwd, setpwd] = useState('')          //使用钩子函数创建 登录密码
  let [hidePwd, sethidePwd] = useState(true)          //使用钩子函数创建 隐藏密码
  let phoneRef = useRef()
  let pwdRef = useRef()

  //当前组件加载时，试着从外部存储中读取保存的手机号和密码（生命周期方法）
  /*useEffect(() => {
    //(async()=>{})() //异步的匿名自调函数
    (async () => {
      let p = await AsyncStorage.getItem('loginphone')
      let w = await AsyncStorage.getItem('loginpwd')
      console.log('登录界面加载时候，读取到的外存数据：', p, w)
      setPhone(p)
      setpwd(w)
    })()
  }, [])
  */
 useEffect(()=>{
  AsyncStorage.getItem('loginphone').then(p=>setPhone(p))
  AsyncStorage.getItem('loginpwd').then(w=>setpwd(w))
 },[])

 
  //执行登录操作 函数
  let doLogin = async () => {
    //验证手机号的合法性（正则表达式）
    let reg = /^1[3-9]\d{9}$/       //正则表达式：以1开头，第二个字符3-9 的中一个
    if (!reg.test(phone)) {
      Alert.alert(
        "错误",
        "手机号格式错误",
        [
          { text: '确定', onPress: () => { } },
          { text: '取消', onPress: () => { } },
        ]
      )
      phoneRef.current.focus()//使用Ref找到当前指向的子组件，让其获得输入焦点
      return
    }
    //验证密码的合法性
    let len = pwd.length
    if (len < 6 || len > 32) {
      Alert.alert('错误', "密码长度非法", [{ text: '确定' }])
      pwdRef.current.focus()//使用Ref找到当前指向的子组件，让其获得输入焦点
      return
    }

    //访问服务器端数据ApI，进行验证登录
    let data = await userModel.login(phone, pwd)
    console.log(data)
    if (data.code == 2000) {
      Toast.show(
        "登录成功" + phone,
        {
          duration:Toast.durations.LONG,
          position:Toast.positions.CENTER
        }
      )
      //在客户端数据库中以键值对形式永久存储登录信息
      AsyncStorage.setItem('loginphone', phone)
      AsyncStorage.setItem('loginpwd', pwd)
    } else {
      Alert.alert("错误", "登录执行失败！服务器返回错误码：" + data.code, [{ text: '确定' }])
    }

    //登录失败，弹出提示消失框，否则跳转到首页

  }




  return (
    <ZhPage bgColor={UIConstants.COLOR_WHITE} >
      {/**F1： LOGO图标*/}
      <Image style={ss.logo} source={logo} />
      {/**引用网络图片方法：<Image style={{width:300, height:300}} source={{uri:'http://116.62.165.70/HarmonyOS.png'}}/>  */}

      {/**F2： 手机号输入框*/}
      <View style={ss.inputGroup}>
        <AntDesign name="user" size={24} color={UIConstants.COLOR_GREEN} />
        <TextInput ref={phoneRef} placeholder='请输入手机号码' style={ss.input} keyboardType='phone-pad' value={phone} onChangeText={val => setPhone(val)} />
        {/*短路逻辑，如有一个为真，后面就不需要走了*/}
        {phone != "" && <AntDesign name="closecircle" size={24} color={UIConstants.COLOR_BLUE} onPress={() => { setPhone('') }} />}
      </View>

      {/**F3： 密码输入框组*/}
      <View style={ss.inputGroup}>
        <AntDesign name="lock1" size={24} color={UIConstants.COLOR_GREEN} />
        <TextInput ref={pwdRef} placeholder='请输入手机号码' style={ss.input} keyboardType='default' value={pwd} onChangeText={val => setpwd(val)} secureTextEntry={hidePwd} />
        <Ionicons name={hidePwd ? "eye-off" : "eye"} size={24} color={UIConstants.COLOR_GRAY} onPress={() => sethidePwd(!hidePwd)} />
      </View>
      {/**F4： 提交按钮*/}
      <View style={ss.butbox} >
        {/* <ZhButton title='登 录' bgColor='#009'></ZhButton> 根据传过来的bgColor参数可单独修改 */}
        <ZhButton title='登 录' bgColor={UIConstants.COLOR_GREEN} onPress={doLogin} />
      </View>



      {/**F5： 忘记密码链接*/}
      <Text  style={ss.pwd}>忘记密码</Text>
    </ZhPage>
  )
}

let ss = StyleSheet.create({
  logo: {
    marginLeft: "auto",
    marginRight: "auto",
    marginTop: UIConstants.SPACE_COL_XL * 3
  },
  inputGroup: {
    backgroundColor: "#F8F8F8",
    //width:"100%",若指定了margin就不能用，否则溢出
    marginHorizontal: UIConstants.SPACE_ROW_XL,
    marginTop: UIConstants.SPACE_COL_LG,
    height: 52,
    borderRadius: UIConstants.BORDER_RADIUS_MD,
    flexDirection: 'row',//改变主轴方向，view默认是弹性容器
    alignItems: "center",//子元素在交叉轴上居中显示
    paddingHorizontal: UIConstants.SPACE_ROW_LG
  },
  input: {
    flex: 1,  //弹性容器中的子元素指定自己的“布局权重“
  },
  butbox: {
    paddingHorizontal: UIConstants.SPACE_ROW_LG,
    marginTop: UIConstants.SPACE_COL_SM * 2
  },
  pwd:{
    marginLeft: "auto",
    marginRight: "auto",
    marginTop: UIConstants.SPACE_COL_XL
  }
})
